<template>
  <div class="app-container">
    <el-form :inline="true" :model="listQuery" @submit.native.prevent>
      <el-form-item label="品牌查询">
        <el-input size="small" v-model="listQuery.q_name"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="small"
          @click="this.getList"
          >查询</el-button
        >
        <el-button icon="el-icon-refresh-left" size="small" @click="reset"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <div class="button-table-margin">
      <el-button
        size="small"
        type="primary"
        @click="addBrand(0)"
        v-permission="['admin/product/brand/create']"
        >添加</el-button
      >
      <el-button
        size="small"
        type="primary"
        @click="addBrand(1)"
        v-permission="['admin/product/brand/update']"
        >修改</el-button
      >
      <el-button
        size="small"
        type="primary"
        @click="deleteBrand"
        v-permission="['admin/product/brand/del']"
        >删除</el-button
      >
    </div>
    <el-table
      ref="singleTable"
      :data="dataList"
      v-loading="listLoading"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @current-change="handleCurrentChange"
    >
      <el-table-column type="index" align="center" width="50">
      </el-table-column>
      <el-table-column label="图片地址">
        <template slot-scope="scope">
          <img
            width="102"
            height="36"
            :src="$imagePath + scope.row.image"
            alt=""
          />
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip property="name" label="品牌名称">
      </el-table-column>
      <el-table-column property="nameFirst" label="首字母"> </el-table-column>
      <el-table-column label="是否推荐">
        <template slot-scope="scope">
          {{ codeBox.BRAND_TOP[scope.row.top] }}
        </template>
      </el-table-column>
      <el-table-column property="createUser" label="创建人"> </el-table-column>
      <el-table-column width="160" property="updateTime" label="创建时间">
      </el-table-column>
      <el-table-column property="updateUser" label="修改人"> </el-table-column>
      <el-table-column width="160" property="updateTime" label="修改时间">
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog :title="dialogTiele" :visible.sync="dialogFormVisible">
      <el-form
        ref="actBrandType"
        :rules="rules"
        :model="actBrandType"
        label-position="right"
        label-width="100px"
      >
        <el-col :span="18">
          <el-form-item label="品牌名称" prop="name">
            <el-input v-model="actBrandType.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="18">
          <el-form-item label="首字母" prop="nameFirst">
            <el-input v-model="actBrandType.nameFirst" maxlength="1"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="品牌图片" prop="image">
            <el-upload
              class="avatar-uploader"
              :action="$imageUrl + '/uploadFileImage'"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="actBrandType.image"
                :src="$imagePath + actBrandType.image"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <span class="form-word-hint"
              >图片不能超过60KB，建议图片高30px，宽60px</span
            >
          </el-form-item>
        </el-col>
        <el-col :span="18">
          <el-form-item label="是否推荐" prop="top">
            <el-radio-group v-model="actBrandType.top">
              <el-radio
                v-for="item in statesList"
                :key="item.value"
                :label="item.value"
                >{{ item.name }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="18">
          <el-form-item label="权重" prop="sort">
            <el-input-number
              v-model="actBrandType.sort"
              :min="0"
              :max="99"
              :step="1"
              step-strictly
            ></el-input-number>
          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="submitForm('actBrandType')">
          提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  fetchBrandList,
  deleteBrand,
  createBrand,
  editBrand,
  updateBrand
} from "@/api/product";
import { getCodeManager, codeToArray, uploadFileImage } from "@/api/all";
import Pagination from "@/components/Pagination";
import { Message } from "element-ui";
export default {
  name: "brandlist",
  components: { Pagination },
  data() {
    return {
      dataList: [],
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        q_name: ""
      },
      currentRow: null,
      dialogFormVisible: false,
      dialogTiele: "",
      currentType: "", // 当前点击类型，0是新增，1是编辑
      statesList: [],
      actBrandType: {
        name: "",
        nameFirst: "",
        top: "",
        sort: "",
        image: ""
      },
      rules: {
        name: [
          { required: true, message: "请输入品牌名称", trigger: "blur" },
          { max: 50, message: "品牌名称不能超过50个字符", trigger: "blur" }
        ],
        nameFirst: [
          { required: true, message: "请输入首字母", trigger: "blur" },
          { max: 1, message: "", trigger: "blur" }
        ],
        top: [{ required: true, message: "是否推荐必选", trigger: "change" }],
        image: [{ required: true, message: "请上传图片", trigger: "change" }],
        sort: [{ required: true, message: "请输入权重", trigger: "blur" }]
      }
    };
  },
  created() {
    getCodeManager("BRAND_TOP", () => {
      this.statesList = codeToArray("BRAND_TOP");
    });
    this.getList();
  },
  methods: {
    handleCurrentChange(val) {
      // 选中当前行数据
      this.currentRow = val;
    },
    // 获取列表数据
    getList() {
      this.listLoading = true;
      fetchBrandList(this.listQuery).then(response => {
        this.dataList = response.data.rows;
        this.total = response.data.total;
        this.listLoading = false;
      });
    },
    handleAvatarSuccess(res, file) {
      const formData = new FormData();
      formData.append("type", "brand");
      formData.append("imageFile", file.raw);
      uploadFileImage(formData).then(result => {
        console.log(result);
        if (result.data.success) {
          this.actBrandType.image = result.data.data;
        }
      });
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 60 < 1;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG和PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 60KB!");
      }
      return isJPG && isLt2M;
    },
    reset() {
      this.listQuery.q_name = "";
      this.getList();
    },
    addBrand(type) {
      // this.$router.push({ path: '/product/brand/brandadd' })
      if (type == 0) {
        // type为0的时候是新增
        this.currentType = 0;
        this.dialogTiele = "品牌新增";
        this.$nextTick(() => {
          this.$refs["actBrandType"].clearValidate();
          this.$refs["actBrandType"].resetFields();
        });
        this.dialogFormVisible = true;
      } else {
        // type为1的时候是编辑
        this.dialogTiele = "品牌编辑";
        if (!this.currentRow) {
          Message.error("请选择操作行。");
          return;
        }
        this.$nextTick(() => {
          this.$refs["actBrandType"].clearValidate();
        });
        this.currentType = 1;
        this.dialogFormVisible = true;
        editBrand({ id: this.currentRow.id }).then(res => {
          this.actBrandType = res.data.data.brand;
          this.actBrandType.top = "" + res.data.data.brand.top;
        });
      }
    },
    editBrand() {
      if (!this.currentRow) {
        Message.error("请选择操作行。");
        return;
      }
      this.$router.push({
        path: "/product/brand/brandedit",
        query: { id: this.currentRow.id }
      });
    },
    deleteBrand() {
      if (!this.currentRow) {
        Message.error("请选择操作行。");
        return;
      }
      if (this.currentRow.status == 3) {
        Message.error("此账号已被删除");
        return;
      }
      this.$confirm("确定删除吗？", "提示", {
        onfirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteBrand({ id: this.currentRow.id }).then(res => {
            if (res.data.success) {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.getList();
            } else {
              this.$message({
                type: "error",
                message: res.data.message
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.currentType == 0) {
            createBrand(this.actBrandType).then(res => {
              if (!res.data.success) {
                Message.error(res.data.message);
                return;
              }
              this.dialogFormVisible = false;
              Message.success("操作成功");
              this.getList();
            });
          } else {
            this.actBrandType.id = this.currentRow.id;
            updateBrand(this.actBrandType).then(res => {
              if (!res.data.success) {
                Message.error(res.data.message);
                return;
              }
              this.dialogFormVisible = false;
              Message.success("操作成功");
              this.getList();
            });
          }
        }
      });
    }
  }
};
</script>
<style scoped>
.filter-container .el-col-6 {
  margin-bottom: 15px;
}
.filter-item {
  margin-bottom: 0;
}
/deep/ .filter-container label {
  font-size: 14px;
  font-weight: 500;
  margin-right: 10px;
}

/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
/deep/ .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
/deep/ [class*="el-col-"] {
  float: none;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  height: 150px;
  display: block;
}
</style>
